#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gmp.h>
#include <pthread.h>

mpf_t y, a, y_old, a_old, aux, aux1;
int i;

void *calc_y(void *args){

    mpf_pow_ui(aux, y_old, 4);
    mpf_ui_sub(aux, 1, aux);
    mpf_sqrt(aux, aux);
    mpf_sqrt(aux, aux);// (1 - y⁴)⁽¹/⁴⁾

    mpf_ui_sub(y, 1, aux);
    mpf_add_ui(aux1, aux, 1);
    mpf_div(y, y, aux1);
}

void *calc_a(void *args){

        mpf_add_ui(aux, y, 1);
        mpf_pow_ui(aux, aux, 4);
        mpf_mul(a, a_old, aux); // a (1 + y)⁴

        mpf_pow_ui(aux1, y, 2);
        mpf_add(aux1, aux1, y);
        mpf_add_ui(aux1, aux1, 1);
        mpf_mul(aux1, aux1, y);
        mpf_mul_2exp(aux1, aux1, 2*i + 3);

        mpf_sub(a, a, aux1);

        mpf_ui_div(a, 1, a);
}


int main (void)
{
    int n = 24;

    pthread_t thread_y, thread_a;

    mpf_set_default_prec (34000000);

    mpf_inits(a, a_old, y, y_old, aux, aux1, NULL);

    //y0
    mpf_set_ui(y_old, 2);
    mpf_sqrt(y_old, y_old);
    mpf_sub_ui(y_old, y_old, 1); //V2 - 1

    //a0
    mpf_set_ui(a_old, 2);
    mpf_sqrt(a_old, a_old);
    mpf_mul_ui(a_old, a_old, 4);
    mpf_ui_sub(a_old, 6, a_old); //6 - 4*V2

    for(i=0;i<n;i++){

        pthread_create(&thread_y, NULL, calc_y, NULL);
        pthread_join(thread_y, NULL);
        pthread_create(&thread_a, NULL, calc_a, NULL);
        pthread_join(thread_a, NULL);

        if(mpf_cmp(a, a_old) == 0)
            break;

        mpf_swap(y_old, y);
        mpf_swap(a_old, a);
    }

    gmp_printf("Iteracoes: %d  %.10000000Ff\n\n", i, a);
    mpf_clears(a, y, a_old, y_old, NULL);

    return 0;
}

